import 'dart:collection';

import 'package:flutter/material.dart';
import 'package:opene/app_constant.dart';
import 'package:opene/app_theme.dart';
import 'package:opene/app_utils.dart';
import 'package:opene/base/base_state.dart';
import 'package:opene/base/loading.dart';
import 'package:opene/base/scan_code.dart';
import 'package:opene/net/network_manager.dart';
import 'package:opene/net/response/base_response.dart';
import 'package:opene/ui/returns/bounce/returnsbounceshipmentscreen.dart';
import 'package:opene/ui/returns/returnsmodel.dart';
import 'package:toast/toast.dart';

class ReturnsBounceScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ReturnsBounceScreenPage();
  }
}

class ReturnsBounceScreenPage extends StatefulWidget {
  @override
  _ReturnsBouncePageState createState() => _ReturnsBouncePageState();
}

class _ReturnsBouncePageState extends BaseState<ReturnsBounceScreen> {
  String pringskuhint = "PrintSKU and label it";
  Bounce bounce;

  @override
  String setTitle({String title}) {
    return !Utils.isEmpty(title) ? title : "Returns:Tracking";
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget getViewBinding() {
    return Padding(
      padding: const EdgeInsets.only(left: 15, top: 10, right: 15),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Expanded(
                flex: 1,
                child: ConstrainedBox(
                  constraints: BoxConstraints(maxHeight: 35),
                  child: TextField(
                    controller: textEditingController,
                    textInputAction: TextInputAction.search,
                    onSubmitted: (String text) {
                      print('Searching for $text');
                      if (Utils.isEmpty(text)) {
                        return;
                      }
                      racking();
                    },
                    // autofocus: true,
                    decoration: InputDecoration(
                      suffixIcon: IconButton(
                        padding: EdgeInsets.all(2.0),
                        icon: Icon(
                          Icons.qr_code_scanner,
                          size: 28,
                          color: MyAppTheme.nearlyBlue,
                        ),
                        onPressed: () {
                          // requestPermissions();
                          // Utils.scanBarcode(context);
                          Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                            return ScanCode();
                          })).then((text) {
                            if (text == null) {
                              return;
                            }
                            setState(() {
                              textEditingController.text = text;
                            });
                            print(text); //拿到扫描结果
                            racking();
                          });
                        },
                      ),
                      border: OutlineInputBorder(
                        borderSide: BorderSide(
                          color: MyAppTheme.nearlyBlue,
                        ),
                        borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                        // 设置焦点之外的边框颜色
                        borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                        // 设置焦点时的边框颜色
                        borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                      ),
                      hintText: "please scan location",
                      filled: true,
                      fillColor: MyAppTheme.white,
                      //隐藏下划线
                      //border: InputBorder.none,
                      hintStyle: TextStyle(color: Colors.grey),
                      contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                    ),
                    onChanged: (text) {
                      code = text;
                    },
                  ),
                ),
              ),
              SizedBox(
                width: 5,
              ),
              GestureDetector(
                onTap: () {},
                child: Icon(
                  Icons.not_interested,
                  size: 35,
                  color: MyAppTheme.nearlyBlue,
                ),
              )
            ],
          ),
          SizedBox(
            height: 5,
          ),
          Visibility(
            visible: bounce == null ? false : true,
            child: Row(
              children: [
                Text(
                  '*',
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(color: MyAppTheme.red, fontSize: 12.0),
                ),
                Expanded(
                  flex: 1,
                  child: Text(
                    Utils.getStringisEmpty(pringskuhint),
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(color: MyAppTheme.color_666666, fontSize: 12.0),
                  ),
                ),
                SizedBox(
                  width: 5,
                ),
                GestureDetector(
                  onTap: () {},
                  child: Icon(
                    Icons.not_interested,
                    size: 35,
                    color: MyAppTheme.nearlyBlue,
                  ),
                )
              ],
            ),
          ),
          SizedBox(
            height: 5,
          ),
          Visibility(
            visible: bounce == null ? false : true,
            child: Row(
              children: [
                Column(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    Text(
                      "SKU/Barcode: ",
                      style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                    ),
                    Text(
                      "QTY: ",
                      style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                    ),
                  ],
                ),
                Expanded(
                  child: Column(
                    children: [
                      Text(
                        bounce == null ? "" : Utils.getStringisEmpty(bounce.sku),
                        style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                      ),
                      Text(
                        bounce == null ? "" : Utils.getStringisInteger(bounce.skuNum),
                        style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  void racking() async {
    Map<String, dynamic> map = new HashMap();
    map["trackingCode"] = textEditingController;

    // 显示加载中对话框
    LoadingIndicator.show(context);

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.preprocessV3CheckTrkExist, params: map);
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
      preprocessV3QueryTrk();
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  void preprocessV3QueryTrk() async {
    Map<String, dynamic> map = new HashMap();
    map["trackingCode"] = textEditingController;

    // 显示加载中对话框
    LoadingIndicator.show(context);

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.preprocessV3QueryTrk, params: map);
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
      setState(() {
        bounce = Bounce.fromJson(baseResponse.data);
        if (bounce == null) {
          return;
        }
        if (bounce.barcodes == null) {
          bounce.barcodes = new List();
        }
        if (!Utils.isEmpty(bounce.sku)) {
          bounce.barcodes.add(bounce.sku);
        }
      });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  @override
  void showFileUploadData(String path, int type, int position, bool isSubmit) {
    // TODO: implement showFileUploadData
  }

  @override
  void setNext() {
    if (Utils.isEmpty(textEditingController.text)) {
      ToastContext().init(context);
      Toast.show("scan tracking number barcode", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }

    if (bounce == null) {
      racking();
      return;
    }

    if (!bounce.regular) {
      ToastContext().init(context);
      Toast.show("Please print the SKU", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => ReturnsBounceShipmentScreen(bounce: bounce)),
    ).then((value) => {
      setState(() {
        textEditingController.text = "";
        hint = "";
      }),
    });
  }

  @override
  void setReset() {
    setState(() {
      textEditingController.text = "";
      hint = "";
      bounce = null;
    });
  }
}
